<template>
  <div class="account-box page">
    <van-nav-bar title="设置" class="bg_white" left-arrow @click-left="$router.go(-1)" />
    <div class="content" ref="webview">
      <div class="cell-group">
        <div class="cell avatarPd van-hairline-j--top">
          <div class="title">
            <span class="name">头像</span>
          </div>
          <div class="value isArrow">
            <img :src="userInfo.userPhoto?userInfo.userPhoto:'/static/images/avatar.png'" @click="openAction" class="avatar" />
            <template v-if="!isApp">
              <van-uploader class="uploader" name="images " v-model="galleryList" :after-read="afterRead" />
            </template>
          </div>
        </div>
      </div>
      <div class="cell-group">
        <div class="cell van-hairline-j--top" @click="goPassword(1)">
          <div class="title">
            <span class="name">修改登录密码</span>
          </div>
          <div class="value isArrow">
          </div>
        </div>
      </div>
      <div class="cell-group">
        <div class="cell van-hairline-j--top" @click="$router.push({ 'path': '/feedback'})">
          <div class="title">
            <span class="name">意见反馈</span>
          </div>
          <div class="value isArrow">
          </div>
        </div>
        <div class="cell van-hairline-j--top" @click="isVersion(true)">
          <div class="title">
            <span class="name">当前版本</span>
          </div>
          <div class="value isArrow">
            <span class="c1">{{version}}</span>
          </div>
        </div>
        <div class="cell van-hairline-j--top" @click="$router.push({ 'path': '/questions/list'})">
          <div class="title">
            <span class="name">帮助中心</span>
          </div>
          <div class="value isArrow">
          </div>
        </div>
      </div>
    </div>
    <div class="exit-login">
      <van-button class="exit" @click="exit">退出登录</van-button>
    </div>
    <div class="avatarFixd" v-if="avatarFixd">
      <span class="van-icon van-icon-cross" @click="closeAvatarFixd"></span>
      <div class="save" @click="fnAvatarSeve">
        <template v-if="isAvatarLoading">
          <van-loading size="20" color="#fff" />
        </template>
        <template v-else>保存</template>
      </div>
    </div>
    <van-action-sheet v-model="isAction" :round="false " @select="selectAction" cancel-text="取消" :actions="actions" description="上传头像" />
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
  name: 'setup',
  data () {
    return {
      isAction: false,
      avatarURL: '',
      avatarFixd: false,
      galleryList: [],
      isAvatarLoading: false,
      isFrontLoading: false,
      imgType: '', // 区分打开的是相机还是相册
      actions: [{ name: '拍照' }, { name: '本机相册' }]
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  destroyed () {
    this.closeAvatarFixd();
  },
  inject: ['isVersion', 'version', 'isApp'],
  methods: {
    goPassword (type) {
      this.$router.push({ 'path': '/password/edit', query: { type: type } });
    },
    exit () {
      this.$store.dispatch('exitLogin');
      localStorage.removeItem('Token');
      this.$router.push({ 'path': '/home' });
    },
    afterRead (data, detail) {
      var fileFormData = new FormData();
      var FiletypeName = null;
      var fileData = null;
      if (!this.isApp) {
        FiletypeName = data.content.replace(/data:image\/([^;]+).*/i, '$1');
      } else {
        fileData = 'data:image/' + detail + ';base64,' + data;
      }
      fileFormData.append('fileType', !this.isApp ? FiletypeName : detail);
      fileFormData.append('base64', !this.isApp ? data.content : fileData);
      // 非APP用web上传
      if (!this.isApp) {
        this.fileUploadAccountImg(fileFormData, detail.name);
      } else {
        return fileFormData;
      }
    },
    // 上传头像
    fileUploadAccountImg (fileFormData, type) {
      this.$toast.loading({ duration: 0 });
      this.$API.global.cardFileUpload(fileFormData).then(res => {
        if (!res.data.code) {
          var _res = res.data;
          if (!this.isApp) {
            this.galleryList = [{ url: _res.src }];
          } else {
            this.isAvatarLoading = false;
            this.closeAvatarFixd();
          }
          this.setAvatarURL(_res.src);
        } else {
          this.$toast(res.data.message);
        }
      });
    },
    // 更新头像
    setAvatarURL (src) {
      this.$toast.loading({ duration: 0 });
      this.$API.user.setAvatar({ imgPath: src }).then(res => {
        if (!res.data.code) {
          this.$store.dispatch('setUserInfo');
          setTimeout(() => {
            this.$toast('修改成功');
          }, 600);
        } else {
          this.$toast(res.data.message);
        }
      });
    },
    // 文件流转base64
    toBase64 (data, callbark) {
      var trans = window.api.require('trans');
      trans.decodeImgToBase64(
        {
          imgPath: 'widget://' + data
        },
        (ret, err) => {
          if (ret.status) {
            callbark && callbark(ret.base64Str.replace(/[\r\n]/g, ''));
          } else {
            console(JSON.stringify(err));
          }
        }
      );
    },
    getPicture (type) {
      window.api.getPicture({
        sourceType: type === 'camera' ? 'camera' : 'album', // 从相册中选择
        encodingType: 'jpg',
        mediaValue: 'pic',
        allowEdit: false,
        destinationType: 'base64', // 返回base64地址
        quality: 70,
        saveToPhotoAlbum: true
      }, (ret, err) => {
        console.log(ret, err);
        this.isAction = false;
        var base64Data = ret.base64Data.replace(/^data:image\/\w+;base64,/, '');
        if (ret.base64Data) {
          this.saveIMG(base64Data);
        } else {
          this.$toast.clear();
        }
      }
      );
    },
    // 保存图片、
    saveIMG (base64Data) {
      var trans = window.api.require('trans');
      this.$toast.loading({ duration: 0 });
      trans.saveImage({
        base64Str: base64Data,
        imgPath: 'fs://img/',
        imgName: 'avatar.png'
      }, (ret, err) => {
        if (ret.status) {
          this.fnAvatarOpen();
        } else {
          console.log(JSON.stringify(err));
        }
      });
    },
    // 关闭裁剪图片
    closeAvatarFixd () {
      var FNImageClip = window.api.require('FNImageClip');
      FNImageClip.close();
      this.avatarFixd = false;
    },
    // 裁剪图片
    fnAvatarOpen () {
      var FNImageClip = window.api.require('FNImageClip');
      this.avatarFixd = true;
      FNImageClip.open({
        rect: {
          x: 0,
          y: 80,
          w: window.api.winWidth,
          h: window.api.winHeight - 80
        },
        srcPath: 'fs://img/avatar.png',
        // highDefinition: true,
        style: {
          mask: '#000',
          clip: {
            w: window.api.winWidth,
            h: window.api.winWidth,
            x: 0,
            y: window.api.winWidth / 2 - 80,
            borderColor: '#0f0',
            borderWidth: 2,
            // appearance: 'circular'
            appearance: 'rectangle'
          }
        },
        mode: 'image',
        fixedOn: window.api.frameName,
        fixed: true
      }, function (ret, err) {
        if (ret) {
          this.$toast.clear();
        }
      });
    },
    // 保存裁剪头像
    fnAvatarSeve () {
      var FNImageClip = window.api.require('FNImageClip');
      this.isAvatarLoading = true;
      FNImageClip.save({
        destPath: 'fs://img/avatar_result.png',
        copyToAlbum: false,
        quality: 1
      }, (ret, err) => {
        if (ret.destPath) {
          this.toBase64(ret.destPath, (base64Str) => {
            var fileFormData = this.afterRead(base64Str, 'png');
            this.fileUploadAccountImg(fileFormData, this.imgType);
          });
        }
      });
    },
    selectAction (action, index) {
      this.getPicture(!index ? 'camera' : 'album');
    },
    openAction () {
      this.isAction = true;
    }
  }
};
</script>
<style lang="less" scoped>
.account-box {
  .avatarFixd {
    position: fixed;
    z-index: 9999999;
    left: 0;
    right: 0;
    top: 0;
    padding: 60px 30px 80px;
    display: flex;
    justify-content: space-between;
    background-color: #000;
    color: #fff;
    font-size: 30px;
    .save {
    }
    .van-icon-cross {
      font-size: 30px;
    }
  }
  .content {
    .cell-group {
      margin: 20px 0;
      .avatarPd {
        padding: 20px 0;
      }
      .avatar {
        width: 80px;
        height: 80px;
        object-fit: contain;
        border-radius: 50%;
        background-color: #eee;
      }
      .uploader {
        position: absolute;
        right: 20px;
        width: 120px;
        opacity: 0;
        z-index: 999;
      }
    }
    .c1 {
      color: #999;
      font-size: 28px;
    }
  }
  .exit-login {
    position: fixed;
    bottom: env(safe-area-inset-bottom);
    left: 0;
    right: 0;
    .van-button__text {
      font-size: 36px;
    }
    .exit {
      width: 100%;
      height: 98px;
      line-height: 98px;
      color: #ff0034;
      border-radius: 0;
      border-top: none;
    }
  }
}
</style>
